package com.pudutech.bluetoothdemo.bluetooth

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.widget.Toast
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException

class ClientSocket {
    private var context: Context? = null
    private var currentDevice: BluetoothDevice? = null
    private var mSocket: BluetoothSocket? = null

    constructor(context: Context?, currentDevice: BluetoothDevice?) {
        this.context = context
        this.currentDevice = currentDevice
        init()
    }


    private fun init(){
        mSocket=currentDevice?.createRfcommSocketToServiceRecord(BluetoothUtils.getUUID())
        GlobalScope.launch {
            try {
                mSocket?.connect()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

    }

    /**
     * 发送数据
     */
    fun sendMessageHandle(msg: String) {
        if (mSocket == null) {
            Toast.makeText(context, "没有连接", Toast.LENGTH_SHORT).show()
            return
        }
        try {
            if (mSocket?.isConnected==true){
                val os = mSocket?.getOutputStream()
                os?.write(msg.toByteArray())
            }else{
                Toast.makeText(context, "连接已断开", Toast.LENGTH_SHORT).show()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun close(){
        mSocket?.close()
    }
}